package world.hezi.handlers;

import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.ListeningStatus;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.MessageEvent;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import world.hezi.bot.BeatsaverBot;
import world.hezi.pojo.AICommand;
import world.hezi.utils.AICommandConsumer;
import world.hezi.utils.CommandAnalyseUtil;
import world.hezi.utils.CommonUtil;
import world.hezi.utils.PicturesUtil;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class AiPicturesHandlers extends SimpleListenerHost {
    @NotNull
    @EventHandler
    public ListeningStatus onMessage(@NotNull MessageEvent event) {
        if (AICommandConsumer.WAITING_INFO.containsKey(event.getSender().getId())){
            AICommand aiCommand = AICommandConsumer.WAITING_INFO.get(event.getSender().getId());
            AICommandConsumer.WAITING_INFO.remove(event.getSender().getId());
            List<String> list = PicturesUtil.getIdsList(event.getMessage());
            if (list.size()!=1){
                AICommandConsumer.WAITING_INFO.remove(event.getSender().getId());
                event.getSubject().sendMessage(new MessageChainBuilder().append(new At(event.getSender().getId())).append(" 取消流程...").build());
            }else {
                String id = list.get(0);
                try {
                    String url = Image.queryUrl(Image.fromId(id));
                    OkHttpClient okHttpClient = new OkHttpClient();
                    final Request request = new Request.Builder()
                            .url(url)
                            .get()
                            .build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            event.getSubject().sendMessage(CommonUtil.getException(e));
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                            ResponseBody body = response.body();
                            String uuid = UUID.randomUUID().toString();
                            String name = "C:\\Users\\65134\\Desktop\\tempBotPic\\"+uuid+".png";
                            try(FileOutputStream fileOutputStream = new FileOutputStream(name)) {
                                fileOutputStream.write(body.bytes());
                                int re = AICommandConsumer.executeForImage(name,aiCommand.getP(),aiCommand.getN(),event,aiCommand.getW(),aiCommand.getH());
                                if (re>0)
                                    event.getSubject().sendMessage("并行任务数："+re+"，词量："+AICommandConsumer.getWordNumber(aiCommand.getP()));
                                else {
                                    event.getSubject().sendMessage("超过并行阈值，任务被阻止");
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });
                }catch (Exception e){
                    event.getSubject().sendMessage(CommonUtil.getException(e));
                }
            }
        }
        String s = event.getMessage().contentToString();
        String sys = "ai绘图功能\n!p:后面跟你想要的(必填)\n!n:后面跟你不想要的\n!w:后面跟宽度\n!h:后面跟高度\n!i:不需要跟任何东西，稍后会接收一张图片作为绘图条件";
        if (s.equals("绘图")||s.equals("绘画")){
            event.getSubject().sendMessage(sys);
        }
        if (s.equals(sys))
            return ListeningStatus.LISTENING;
        s = s.replaceAll("！","!")
                .replaceAll("：",":")
                .replaceAll("\n","")
                .toLowerCase();
        Map<String,String> commandMap = CommandAnalyseUtil.analysisCommand(new String[]{"!i:", "!w:", "!p:", "!h:", "!n:"},s);
        int w = 512;
        int h = 512;
        if (commandMap.size()>0&&commandMap.containsKey("!p:")){
            try {
                w = Integer.parseInt(commandMap.getOrDefault("!w:", "512").trim());
                h = Integer.parseInt(commandMap.getOrDefault("!h:", "512").trim());
            }catch (Exception e){

            }
            if (w*h>1048576||w>2048||h>2048){
                event.getSubject().sendMessage("长乘宽不能大于1048576,长或者宽不能大于2048");
                return ListeningStatus.LISTENING;
            }
            String p = commandMap.get("!p:");
            String n = commandMap.getOrDefault("!n:", "");
            int re;
            if (commandMap.containsKey("!i:")){
                AICommandConsumer.WAITING_INFO.put(event.getSender().getId(),new AICommand(p,n,w,h));
                re = -10;
            }else {
                re = AICommandConsumer.execute(p,n,event,w,h);
            }
            if (re>0)
                event.getSubject().sendMessage("并行任务数："+re+"，词量："+AICommandConsumer.getWordNumber(p));
            else if (re==-10){
                event.getSubject().sendMessage(new MessageChainBuilder().append(new At(event.getSender().getId())).append(" 开始接收图片...").build());
            }else {
                event.getSubject().sendMessage("超过并行阈值，任务被阻止");
            }
        }
        return ListeningStatus.LISTENING;
    }
}
